;(function($, window, document,undefined) {

    //MyPager
    var MyPager = function (ele, opt) {
        var _this = this;
        this.$element = ele;
        this._loading = false;
        this.curPage = 0;
        this.defaults = {
            url: null,
            infiniteEle: $(document.body),
            loadmoreClass: "weui-loadmore"
        };
        this.options = $.extend({}, this.defaults, opt);

        this.options.infiniteEle.infinite().on("infinite", function() {
            _this.load();
        });
    };

    MyPager.prototype = {
        load : function() {
            var _this = this;
            if(this._loading) {
                return;
            }
            this._loading = true;
            this.curPage = this.curPage + 1;
            var url = this.options.url + (this.options.url.indexOf("?") == -1 ? "?" : "&") + 'currentPage=' + this.curPage;
            $.get(url, function(result){
                _this.$element.append(result);
                if($("#isLastPage", _this.$element).length > 0) {
                    _this.options.infiniteEle.destroyInfinite();
                    $("." +  _this.options.loadmoreClass, _this.$element.parent()).hide();
                }
                _this._loading = false;
            });
            return this;
        },

        reload : function(url) {
            if(url) {
                this.options.url = url;
            }
            this.curPage = 0;
            this.$element.empty();
            $("." +  this.options.loadmoreClass).show();
            return this.load();
        }
    };

    $.fn.myPage = function (options) {
        // This is the easiest way to have default options.
        var myPager = new MyPager(this, options);
        return myPager.load();
    };


})(jQuery, window, document);

function getRootPath_dc() {
    return window.location.protocol + '//' + window.location.host;
}

function initSelect(id, url, options) {
    var $this;
    if(id instanceof jQuery) {
        $this = id;
    }
    else {
        $this = $("#" + id);
    }

    var valueFieldId = options.valueFieldId;

    if(options && options.defaultTitle && options.defaultTitle != 'null') {
        $this.val(options.defaultTitle);
    }

    if(options && options.defaultValue && options.defaultValue != 'null') {
        $this.attr("data-values", options.defaultValue);
    }

    if(valueFieldId) {
        initSelectValueField($this, valueFieldId, options.defaultValue);
    }

    var $_select;
    $.ajax({
        type: 'GET',
        url: url,
        dataType: 'json',
        success: function (reply) {
            options = $.extend(true, {
                items: reply,
                onChange: function(item) {
                    initSelectValueField($this, valueFieldId, item.values);
                }
            }, options || {});

            $_select = $this.select(options);
        },
        data: {},
        async: false
    });
    return $_select;
}

function updateSelect($_select, url) {
    $.getJSON(url, function (reply) {
        config =  {items: reply};
        $_select.select("update", config)
    });
}

function initSelectValueField($selectObj, valueFieldId, values) {
    var valueField = $("#" + valueFieldId);
    if(valueField.length < 1) {
        valueField = $('<input type="hidden"/>');
        valueField.attr("name", valueFieldId);
        valueField.attr("id", valueFieldId);
        valueField.insertAfter($selectObj);
    }
    if(values) {
        valueField.val(values);
    }
}

$.validator.setDefaults({
    submitHandler: function() {
        alert("submitted!");
    },
    showErrors: function(map, list) {
        this.currentElements.each(function () {
            var $cell = $(this).closest(".weui-cell");
            $cell.removeClass("weui-cell_warn");
            $(".weui-icon-warn", $cell).parent().remove();
        });
        $.each(list, function(index, error) {
            var $element = $(error.element);
            var $cell = $element.closest(".weui-cell");
            $cell.addClass("weui-cell_warn");
            if(error.element.type != "textarea") {
                $('<div class="weui-cell__ft"><i class="weui-icon-warn"></i></div>').appendTo($cell);
            }
        });
    }
});

$(function() {
    FastClick.attach(document.body);

    $("div[liger], td[liger], span[liger], input[liger]").each(function () {
        var $this = $(this);
        var config = strToJson($this.attr("liger"));
        if ("config" == config["type"]) {
            $.get('/app/common/config/value?configCode=' + config['configCode'] + "&configValue=" + $this.html(), function (result) {
                $this.html(result);
            });
        }
        else if("select" == config["type"]) {
            initSelect($this, config["url"], {valueFieldId: config["valueFieldId"], defaultTitle : $this.val(), defaultValue: $this.attr("rel")});
        }
        else if("checkBox" == config["type"]){
            $.get('/app/common/config/checkBoxValue?configCode=' + config['configCode'] + "&configValue=" + $this.html(), function (result) {
                $this.html(result);
            });
        }
    });

    $(".weui-textarea").keyup(function () {
        var $this = $(this);
        var $counter = $this.next(".weui-textarea-counter");
        $counter.children("span").html($this.val().length);
    });

    $("td[liger], span[liger], div[liger],input[liger]").each(function() {
        var $this = $(this);
        var config = strToJson($this.attr("liger"));
        if("code" == config["type"]) {
            $.get('/app/common/code/value?codeKey='+ config['key'] + "&codeNo=" + $this.html(), function(result){
                $this.html(result);
            });
        }
        else if("select" == config["type"]) {
            $.get('/app/common/code/value?codeKey='+ config['key'] + "&codeNo=" + $this.attr("rel"), function(result){
                $this.val(result);
            });
        }
    });

    $(".weui-cells_form input[required]").each(function () {
       var $this = $(this);
       try{
           $("<span style='color:red'>*</span>").appendTo($(".weui-label", $this.closest(".weui-cell")));
       }
       catch(e) {

       }
    });
});

function ajaxDo(url, callback) {
    $.ajax({
        url : url,
        type : "GET",
        success : function(reply) {
            if(callback) {
                callback(reply);
            }
            else {
                if (reply.success) {
                    if (reply.message) {
                        $.toast(reply.message);
                    }
                    window.reload();
                } else {
                    if (reply.message) {
                        $.alert(reply.message);
                    }
                }
            }
        }
    });
}
